package com.bfly.mall.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.bfly.common.ResponseUtil;
import com.bfly.common.util.FileUtil;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.config.ResourceConfigure;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.core.security.ActionModel;
import com.bfly.core.security.PermissionCheck;
import com.bfly.mall.system.entity.SysConfig;
import com.bfly.mall.system.enums.SysConfigType;
import com.bfly.mall.system.service.ISysConfigService;
import com.bfly.mall.wechat.minipro.service.WeChatMiniProAPi;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统配置
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/9/18 11:09
 */
@RestController
@RequestMapping(value = "/manage/config")
public class SysConfigController extends BaseController {

    @Autowired
    private ISysConfigService configService;

    /**
     * 系统配置
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/17 21:30
     */
    @GetMapping(value = {"/wechat/list", "/sys/list"})
    public void list(HttpServletResponse response, @RequestParam(value = "type") int type) {
        SysConfigType configType = SysConfigType.get(type);
        Object config;
        switch (configType) {
            case WX_MINIPRO:
                config = configService.getWxMiniProConfig();
                break;
            case WX_MP:
                config = configService.getWxMpConfig();
                break;
            case WX_PAY:
                config = configService.getWxPayConfig();
                break;
            case ORDER:
                config = configService.getOrderConfig();
                break;
            case WATER_MARK:
                config = configService.getWaterMarkConfig();
                break;
            case SYSTEM:
                config = configService.getSystemConfig();
                break;
            default:
                throw new ServiceResponseException(SysError.PARAM_ERROR, "未知的配置类型!");
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(config));
    }

    /**
     * 保存配置信息
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/18 12:44
     */
    @PostMapping(value = {"/wechat/save", "/sys/save"})
    @ActionModel(value = "保存配置信息")
    public void save(HttpServletResponse response, @RequestBody JSONObject json) {
        int type = json.getInteger("type");
        json.remove("type");

        List<SysConfig> list = new ArrayList<>();
        for (String key : json.keySet()) {
            SysConfig configDTO = new SysConfig();
            configDTO.setType(type);
            configDTO.setName(key);
            configDTO.setData(json.get(key).toString());
            list.add(configDTO);
        }
        configService.merge(type, list);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 获得操作系统字体集合
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/6/29 17:55
     */
    @GetMapping(value = "/fonts")
    @PermissionCheck(required = false)
    public void getFonts(HttpServletResponse response) {
        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String fonts[] = e.getAvailableFontFamilyNames();
        ResponseUtil.writeJson(response, ResponseData.getSuccess(fonts));
    }


    /**
     * 上传配置文件--证书之类的重要文件
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/12/9 21:10
     */
    @PostMapping(value = "/wechat/upload")
    @ActionModel(value = "文件配置上传")
    public void uploadFile(@RequestPart MultipartFile file, HttpServletResponse response) throws Exception {
        String targetDir;
        targetDir = ResourceConfigure.getConfig().getSecurityRootPath();
        targetDir = targetDir + File.separator;
        FileUtil.mkdir(targetDir);

        String targetFile = targetDir + File.separator + file.getOriginalFilename();
        boolean result = FileUtil.writeFile(file.getInputStream(), targetFile);
        if (!result) {
            throw new RuntimeException("文件上传失败!");
        }
        String relativePath = FilenameUtils.separatorsToUnix("/" + Paths.get(ResourceConfigure.getConfig().getResourceRootPath()).relativize(Paths.get(targetFile)));
        JSONObject json = new JSONObject();
        json.put("path", relativePath);
        json.put("url", file.getOriginalFilename());
        json.put("name", file.getOriginalFilename());
        ResponseUtil.writeJson(response, ResponseData.getSuccess(json));
    }

    /**
     * 生成小程序二维码
     *
     * @author andy_hulibo@163.com
     * @date 2020/12/20 14:11
     */
    @GetMapping(value = "/generate/qrcode")
    public void generateMiniProQrCode(HttpServletResponse response, @RequestParam("path") String path) {
        String code = WeChatMiniProAPi.createQRCode(path);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(code));
    }

    /**
     * 生成小程序码
     *
     * @author andy_hulibo@163.com
     * @date 2020/12/20 14:11
     */
    @GetMapping(value = "/generate/acode")
    public void generateMiniProACode(HttpServletResponse response, @RequestParam("path") String path) {
        String code = WeChatMiniProAPi.getWxACode(path);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(code));
    }
}
